# -*- coding: utf-8 -*-
import os
import json
from core import YamlLoad
from core.DataReplace import data_processing
from core.Response import HttpResponse
from core.session import HttpRequest
from config.config import log_separator
from utils.logger import log

"""
测试用例统一执行方法
"""


def run_test(data):
    def _record_case_status(case_name: str, status: str) -> None:
        try:
            run_id = os.environ.get("HOK_RUN_ID")
            if not run_id:
                return
            out_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), "output")
            os.makedirs(out_dir, exist_ok=True)
            status_file = os.path.join(out_dir, f"run_{run_id}_status.jsonl")
            with open(status_file, "a", encoding="utf-8") as f:
                f.write(json.dumps({"name": case_name, "status": status}, ensure_ascii=False) + "\n")
        except Exception:
            pass

    case_name = data.get("name") or ""

    data = data_processing(data)
    temp = HttpRequest()
    # 开始执行前先记录为 running，便于状态页第一时间展示用例名
    if case_name:
        _record_case_status(case_name, "running")
    try:
        # 发送http请求
        response = temp.session_request(data)
        # 处理响应信息
        log.info(log_separator + "Response processing" + log_separator)
        res = HttpResponse(response, temp.response_time_ms)
        # 提取数据到extract文件中
        extract = data.get("extract")
        if extract != "None" and extract:
            extract_data = res.extract_value(extract)
            if extract_data:
                YamlLoad.write_center_params(extract_data)
        # 断言的处理
        validate_list = data.get("validate")
        if validate_list != "None" and validate_list:
            result = res.validate(validate_list)
            _record_case_status(case_name, "passed" if result else "failed")
            return result
        _record_case_status(case_name, "passed")
    except AssertionError:
        _record_case_status(case_name, "failed")
        raise
    except Exception:
        _record_case_status(case_name, "broken")
        raise
    finally:
        log.info(log_separator + "end" + log_separator + '\n\n')
